<template>
  <div class="user-manage-page">
    <el-card>
      <div class="header-bar">
        <span class="title">用户管理</span>
        <el-button type="primary" size="small" @click="openEditDialog()">新增用户</el-button>
      </div>
      <el-table :data="userList" border>
        <el-table-column prop="username" label="用户名" min-width="110" />
        <el-table-column prop="realname" label="姓名" min-width="110" />
        <el-table-column prop="roles" label="角色" min-width="140">
          <template #default="scope">
            <el-tag v-for="r in scope.row.roles" :key="r" style="margin-right:4px;">
              {{ getRoleName(r) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="140" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑/新增用户弹窗 -->
    <el-dialog v-model="dialogVisible" :title="editUser.id ? '编辑用户' : '新增用户'" width="400px">
      <el-form :model="editUser" :rules="formRules" ref="formRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUser.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="realname">
          <el-input v-model="editUser.realname" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="editUser.roles" multiple placeholder="请选择角色">
            <el-option v-for="role in roleList" :key="role.id" :label="role.rolename" :value="role.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 角色模拟数据
const defaultRoles = [
  { id: 'admin', rolename: '管理员' },
  { id: 'editor', rolename: '编辑者' },
  { id: 'viewer', rolename: '只读用户' }
]

// 初始化角色数据
const roleList = ref([])
function initRoles() {
  const local = JSON.parse(localStorage.getItem('roleList') || 'null')
  if (!local) {
    localStorage.setItem('roleList', JSON.stringify(defaultRoles))
    roleList.value = defaultRoles
  } else {
    roleList.value = local
  }
}

// 用户模拟数据
const defaultUsers = [
  { id: 1, username: 'admin', realname: '管理员', roles: ['admin'], email: 'admin@test.com' },
  { id: 2, username: 'user1', realname: '张三', roles: ['editor'], email: 'user1@test.com' },
  { id: 3, username: 'user2', realname: '李四', roles: ['viewer'], email: 'user2@test.com' }
]

const userList = ref([])
function initUsers() {
  const local = JSON.parse(localStorage.getItem('userList') || 'null')
  if (!local) {
    localStorage.setItem('userList', JSON.stringify(defaultUsers))
    userList.value = defaultUsers
  } else {
    userList.value = local
  }
}

onMounted(() => {
  initRoles()
  initUsers()
})

// 查找角色名
function getRoleName(id) {
  const r = roleList.value.find(r => r.id === id)
  return r ? r.rolename : id
}

// 编辑/新增用户弹窗
const dialogVisible = ref(false)
const editUser = reactive({
  id: null,
  username: '',
  realname: '',
  email: '',
  roles: []
})
const formRef = ref()
const formRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  roles: [{ required: true, type: 'array', min: 1, message: '请选择角色', trigger: 'change' }]
}

function openEditDialog(row = null) {
  if (row) {
    editUser.id = row.id
    editUser.username = row.username
    editUser.realname = row.realname
    editUser.email = row.email
    editUser.roles = [...row.roles]
  } else {
    editUser.id = null
    editUser.username = ''
    editUser.realname = ''
    editUser.email = ''
    editUser.roles = []
  }
  dialogVisible.value = true
}

function saveUser() {
  formRef.value.validate((valid) => {
    if (!valid) return
    let users = JSON.parse(localStorage.getItem('userList') || '[]')
    if (editUser.id) {
      // 编辑
      users = users.map(u => u.id === editUser.id ? { ...editUser } : u)
    } else {
      // 新增
      const maxId = users.reduce((max, u) => Math.max(max, u.id), 0)
      users.unshift({ ...editUser, id: maxId + 1 })
    }
    localStorage.setItem('userList', JSON.stringify(users))
    userList.value = users
    ElMessage.success('保存成功！')
    dialogVisible.value = false
  })
}

function deleteUser(row) {
  const users = userList.value.filter(u => u.id !== row.id)
  localStorage.setItem('userList', JSON.stringify(users))
  userList.value = users
  ElMessage.success('已删除！')
}
</script>

<style scoped>
.user-manage-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 95vh;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.title {
  font-size: 20px;
  font-weight: 600;
}
</style>
